package com.flute.icrawler.app.distributed;

import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Iterator;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.client.Constants;
import com.flute.haflute.jobbox.base.CloudJobCenterController;
import com.flute.haflute.jobbox.base.StatusReporter;
import com.flute.icrawler.app.task.entity.CrawlTask;
import com.flute.icrawler.config.CrawlConfig;
import com.flute.icrawler.config.CrawlConfigUtil;
import com.flute.icrawler.framework.framework.JobServerController;

public class DistributedJobController4Server implements
		CloudJobCenterController {
	private JobServerController controller = null;

	private static Logger logger = LoggerFactory
			.getLogger(DistributedJobController4Server.class);

	public DistributedJobController4Server() throws ClassNotFoundException {
	}

	/*
	 * @see com.cpkf.yyjd.cloud.base.CloudJobCenterController#getJobAgent()
	 */
	@Override
	public Remote getJobAgent() {
		Remote remote = controller.getCrawlUrlPool();
		try {
			UnicastRemoteObject.exportObject(remote);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return remote;
	}

	/*
	 * @see
	 * com.cpkf.yyjd.cloud.base.CloudJobCenterController#start(com.cpkf.yyjd
	 * .cloud.base.StatusReporter)
	 */
	@Override
	public boolean start(StatusReporter reporter) {
		controller.addCrawlListener(new DistributedCrawlJobListener(reporter));
		controller.start();

		return true;
	}

	/**
	 * 以当前的配置来启动爬虫
	 * 
	 * @param crawlConfig
	 * @throws ClassNotFoundException
	 */
	private void startCrawler(CrawlConfig crawlConfig)
			throws ClassNotFoundException {

		controller = new JobServerController(crawlConfig);

	}

	/**
	 * 任务结束的回调函数
	 */
	@Override
	public boolean end() {
		return false;
	}

	@Override
	public void initJob(Serializable config) {
		String fileName = "";
		if (config instanceof Properties) {
			Properties props = (Properties) config;
			Iterator<Object> ite = props.keySet().iterator();
			while (ite.hasNext()) {
				String key = (String) ite.next();
				if (key.startsWith(Constants.FILEPREFIX
						+ CrawlTask.CONFIG_FILENAME)) {
					fileName = props.getProperty((String) key);
				}
			}

			logger.info("fileName=" + fileName);
		}

		try {
			startCrawler(CrawlConfigUtil.newCrawlConfig(fileName));
		} catch (ClassNotFoundException e) {
			logger.error(e.getLocalizedMessage());
		}
	}

}
